#!/bin/bash
# XDevice 依赖检查脚本

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo "🔍 检查 XDevice 构建依赖..."
echo

missing_deps=()
optional_missing=()

# 检查必需的包
required_packages=(
    "gcc:gcc --version"
    "make:make --version" 
    "pkg-config:pkg-config --version"
)

required_libs=(
    "libevent:pkg-config --exists libevent"
    "openssl:pkg-config --exists openssl"
    "zlib:pkg-config --exists zlib"
    "liblz4:pkg-config --exists liblz4"
    "libzstd:pkg-config --exists libzstd"
    "uuid:pkg-config --exists uuid"
)

# 检查可选包  
optional_libs=(
    "liburing:pkg-config --exists liburing"
    "numa:pkg-config --exists numa"
    "rdmacm:pkg-config --exists rdmacm"
    "ibverbs:pkg-config --exists libibverbs"
)

optional_tools=(
    "valgrind:which valgrind"
    "gdb:which gdb"
    "doxygen:which doxygen"
    "dot:which dot"
)

check_dependency() {
    local name="$1"
    local cmd="$2"
    local is_optional="$3"
    
    if eval "$cmd" >/dev/null 2>&1; then
        echo -e "✅ ${GREEN}$name${NC}"
        return 0
    else
        if [ "$is_optional" = "true" ]; then
            echo -e "⚠️  ${YELLOW}$name (可选)${NC}"
            optional_missing+=("$name")
        else
            echo -e "❌ ${RED}$name${NC}"
            missing_deps+=("$name")
        fi
        return 1
    fi
}

echo "📦 检查必需工具..."
for pkg in "${required_packages[@]}"; do
    IFS=':' read -r name cmd <<< "$pkg"
    check_dependency "$name" "$cmd" "false"
done

echo
echo "📚 检查必需库..."
for lib in "${required_libs[@]}"; do
    IFS=':' read -r name cmd <<< "$lib"
    check_dependency "$name" "$cmd" "false"
done

echo
echo "🚀 检查可选库 (性能增强)..."
for lib in "${optional_libs[@]}"; do
    IFS=':' read -r name cmd <<< "$lib"
    check_dependency "$name" "$cmd" "true"
done

echo
echo "🔧 检查开发工具..."
for tool in "${optional_tools[@]}"; do
    IFS=':' read -r name cmd <<< "$tool"
    check_dependency "$name" "$cmd" "true"
done

echo
echo "📋 检查结果摘要:"

if [ ${#missing_deps[@]} -eq 0 ]; then
    echo -e "✅ ${GREEN}所有必需依赖都已安装${NC}"
else
    echo -e "❌ ${RED}缺少以下必需依赖:${NC}"
    for dep in "${missing_deps[@]}"; do
        echo "   - $dep"
    done
    echo
    echo "💡 安装命令:"
    echo "   Ubuntu/Debian: sudo apt-get install build-essential libevent-dev libssl-dev zlib1g-dev liblz4-dev libzstd-dev uuid-dev"
    echo "   CentOS/RHEL: sudo yum groupinstall \"Development Tools\" && sudo yum install libevent-devel openssl-devel zlib-devel lz4-devel libzstd-devel libuuid-devel"
fi

if [ ${#optional_missing[@]} -gt 0 ]; then
    echo -e "⚠️  ${YELLOW}以下可选依赖未安装 (建议安装以获得更好性能):${NC}"
    for dep in "${optional_missing[@]}"; do
        echo "   - $dep"
    done
fi

echo

if [ ${#missing_deps[@]} -eq 0 ]; then
    echo -e "🎉 ${GREEN}系统已准备就绪，可以构建 XDevice!${NC}"
    exit 0
else
    echo -e "🚫 ${RED}请先安装缺失的依赖再进行构建${NC}"
    exit 1
fi
